﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.App.Api.Application.Command.Detail.Slaughter;
using Traceability.App.ErrorCount;
using Traceability.App.InfrasIntructure;
using Traceability.App.Model.Cultivation;
using Traceability.App.Model.DeepProcessing;
using Traceability.App.Model.Slaughter;

namespace Traceability.App.Api.Application.Handler.Detail.Slaughter
{
    public class AddSlaughterCompanyHandler : IRequestHandler<AddSlaughterCommpanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SlaughterCommpanyModel> _slaucomRepo;
        private readonly IBaseRepository<DeepProcessingCompanyModel> _deepProcessRepo;
        private readonly IMapper _mapper;

        public AddSlaughterCompanyHandler(
            IBaseRepository<SlaughterCommpanyModel> slaucomRepo,
            IBaseRepository<DeepProcessingCompanyModel> deepProcessRepo,
            IMapper mapper)
        {
            _slaucomRepo = slaucomRepo;
            _deepProcessRepo = deepProcessRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddSlaughterCommpanyCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            // 如果请求中有公司名称，检查并更新深加工企业信息
            if (!string.IsNullOrEmpty(request.CompanyName))
            {
                var deepProcessCompany = await _deepProcessRepo.GetAll()
                    .FirstOrDefaultAsync(c => c.Batch == request.Batch && !c.IsDeleted);

                if (deepProcessCompany != null && string.IsNullOrEmpty(deepProcessCompany.CompanyName))
                {
                    deepProcessCompany.CompanyName = request.CompanyName;
                    await _deepProcessRepo.Update(deepProcessCompany);
                }
            }

            // 添加屠宰企业信息
            var model = _mapper.Map<SlaughterCommpanyModel>(request);
            var result = await _slaucomRepo.Add(model);

            res.Datas = result;
            res.Code = result > 0 ? ApiEnum.Success : ApiEnum.Fail;
            res.Msg = result > 0 ? "添加屠宰企业信息成功" : "添加屠宰企业信息失败";

            return res;
        }
    }
}
